package net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UPDClient {

    private static final SocketAddress address =
            new InetSocketAddress("localHost",4096);

    public static void main4(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("------------------------------");
            System.out.print("请输入要展示的目录：");
            String request = scanner.nextLine() + "\3";

            //通过getBytes方法（+标准字符集参数）将请求的数据转为UTF_8格式的byte
            byte[] requestData = request.getBytes(StandardCharsets.UTF_8);
            //然后创建数据报接收该数组
            DatagramPacket requestPacket =
                    new DatagramPacket(requestData, requestData.length, address);
            socket.send(requestPacket);

            byte[] responseData = new byte[2048];
            DatagramPacket responsePacket =
                    new DatagramPacket(responseData, responseData.length);
            socket.receive(responsePacket);
            System.out.print("该目录下的文件列表为：");

            int next = 0;
            for (int i = 0; i < requestData.length; i++) {
                byte b = requestData[i];
                //结束符退出
                if (b == '\3') {
                    break;
                }
                //换行符解析
                if (b == '\n') {
                    String fileName = new String(responseData, next, i-next);
                    next = i + 1;
                    System.out.println(fileName);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(4096);
        byte[] bytes = "hello pussy".getBytes();

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        socket.send(packet);
    }

}
